package com.software.loginregister.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.software.loginregister.R;
import com.software.loginregister.api.PostApi;
import com.software.loginregister.entity.Post;
import com.software.loginregister.entity.Result;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PublishPostActivity extends AppCompatActivity {

    private EditText etPostTitle;
    private EditText etPostContent;
    private ImageView ivPostImage;
    private Button btnPublish;
    private boolean isSavingDraft = false;
    private SharedPreferences sharedPreferences;
    private ProgressDialog progressDialog;

    private PostApi postApi;
    private static final String TAG = "PublishPostActivity";
    private Long userId;
    private TextView tvPublishPost;

    private Uri postImageUri;
    private Button addImageButton;

    private static final int PICK_IMAGE_REQUEST = 1;
    private File compressedImageFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_post);

        initViews();

        postApi = RetrofitClient.getInstance().create(PostApi.class);
        ClickListener();
        setStatusBar();
    }

    private void ClickListener() {
        tvPublishPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publishPost();
            }
        });

        ivPostImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickImage();
            }
        });
        addImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickImage();
            }
        });
    }


    private void initViews() {
        etPostTitle = findViewById(R.id.et_post_title);
        etPostContent = findViewById(R.id.et_post_content);
        ivPostImage = findViewById(R.id.iv_post_image);
        tvPublishPost = findViewById(R.id.tv_publish_post);
        addImageButton = findViewById(R.id.btn_add_image);
    }


    private void publishPost() {

        try {
            // 获取实际的用户ID
            userId = SharedPreferencesUtil.getUserId(this);
            if (userId == null) {
                Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
                dismissProgressDialog();
                return;
            }
            Log.d(TAG, "使用登录用户ID: " + userId);
            // ...
        } catch (Exception e) {
            Log.d(TAG, "发生异常", e);
            e.printStackTrace();
        }

        String title = etPostTitle.getText().toString().trim();
        String content = etPostContent.getText().toString().trim();

        if (title.isEmpty() || content.isEmpty()) {
            Toast.makeText(this, "标题和内容不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建 RequestBody 对象
        RequestBody titlePart = RequestBody.create(MediaType.parse("text/plain"), title);
        RequestBody userIdPart = RequestBody.create(MediaType.parse("text/plain"), userId.toString());
        RequestBody contentPart = RequestBody.create(MediaType.parse("text/plain"), content);

        // 处理图片
        MultipartBody.Part imagePart = null;
        if (compressedImageFile != null) {
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), compressedImageFile);
            imagePart = MultipartBody.Part.createFormData("postImage", compressedImageFile.getName(), requestFile);
        }

        // 发起网络请求
        Call<Result<Post>> call = postApi.createPost(titlePart, userIdPart, contentPart, imagePart);
        call.enqueue(new Callback<Result<Post>>() {
            @Override
            public void onResponse(Call<Result<Post>> call, Response<Result<Post>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Result<Post> result = response.body();
                    if (result.getCode() == 1) { // 假设 1 表示成功
                        Toast.makeText(PublishPostActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(PublishPostActivity.this, "发布失败: " + result.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(PublishPostActivity.this, "发布失败，请稍后重试", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result<Post>> call, Throwable t) {
                Toast.makeText(PublishPostActivity.this, "网络错误，请检查网络连接", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "网络请求失败", t);
            }
        });
    }


    private void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private void setStatusBar() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);
    }

    // 在 PublishPostActivity 中添加以下方法
    private File compressImage(Uri imageUri) {
        try {
            // 创建临时文件来存储压缩后的图片
            File outputDir = getCacheDir();
            File outputFile = File.createTempFile("compressed_", ".jpg", outputDir);

            // 获取原始图片的 Bitmap
            Bitmap originalBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);

            // 计算压缩比例
            int width = originalBitmap.getWidth();
            int height = originalBitmap.getHeight();
            float ratio = 1.0f;

            // 如果图片太大，计算压缩比例
            if (width > 2048 || height > 2048) {
                ratio = Math.min(2048f / width, 2048f / height);
                width = (int) (width * ratio);
                height = (int) (height * ratio);
            }

            // 创建压缩后的 Bitmap
            Bitmap compressedBitmap = Bitmap.createScaledBitmap(originalBitmap, width, height, true);

            // 使用 JPEG 格式压缩图片
            FileOutputStream fos = new FileOutputStream(outputFile);
            compressedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();

            // 释放 Bitmap 资源
            originalBitmap.recycle();
            compressedBitmap.recycle();

            // 检查压缩后的文件大小
            if (outputFile.length() > 1024 * 1024) { // 1MB
                // 如果还是太大，继续压缩
                Bitmap recompressBitmap = BitmapFactory.decodeFile(outputFile.getAbsolutePath());
                fos = new FileOutputStream(outputFile);
                recompressBitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);
                fos.flush();
                fos.close();
                recompressBitmap.recycle();
            }

            return outputFile;
        } catch (Exception e) {
            Log.e(TAG, "压缩图片失败", e);
            return null;
        }
    }



    private void pickImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            if (selectedImage != null) {
                postImageUri = selectedImage;
                ivPostImage.setImageURI(selectedImage);
                // 压缩图片
                compressedImageFile = compressImage(selectedImage);
            }
        }
    }


}